<?php
namespace Wechat\Controller;
use Common\Controller\AdminbaseController;
use Home\Service\AccountService;
use Home\Service\WechatService;
// +----------------------------------------------------------------------
// | Date:2017年12月11日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
class TmessageController extends AdminbaseController{
    
    protected $model;
    public function  _initialize(){
        
        $this->model = M('Kfmessage');
    }
    
    public function index(){
        $list = $this->lists($this->model,$where,$order,'id,title');
        $this->assign('list',$list);
        $this->display();
       
    }
    
    /**
     * 获取全部员工的openid,发送客服消息
     * 
     * 
     * date:2017年12月11日
     * author: EK_熊
     */
    public function send_all(){
        $id = I('id');
        $count = 0;
        if (empty($id)) $this->error('参数错误！');
        
        $content = $this->model->where(['id'=>$id])->getField('content');
        
        $account = new AccountService();
        $user_map = [
            'wx_openid'=>['neq',' '],
            'status'=>1,
        ];
        $all_user = $account->get_all_user_baseinfo('sn,wx_openid',$user_map);

        foreach ($all_user as $sn=>$wx_openid) {
           $ret = $this->send_custom_message($wx_openid, $content);
           if ($ret === true) {
               $count++;
           }else{
               $this->error('系统异常暂停发送！！');
           }
        }
        
        $this->success("已成功推送了{$count}条消息");
        
    }
    
    /**
     * 预览
     * 
     * date:2017年12月12日
     * author: EK_熊
     */
    public function preview(){
        $openid = I('openid');
        $content = I('content');
        if (empty($openid)) $this->error('请选择测试人员');
        
        $ret = $this->send_custom_message($openid, $content);
        if ($ret === true){
            $this->success('发送成功！');
        }
        $this->error($ret);
    }
    
    
    
        
    private function send_custom_message($openid,$content){
        $wechat = new WechatService();
        $send_message = $wechat->send_custom_message($openid, $content);
        if ($send_message){
            return true;
        }
        return $wechat->getError();
    }
    
    
}